﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Reflection;
using System.Text.RegularExpressions;

/*
 * JavaScriptSerializer ser = new JavaScriptSerializer();
 * ser.RegisterConverters(new[] { new JSONConverter<MyClass>('<subtract column name>') });
 * ser.Serialize(Data);
*/
public class JSONConverter<T> : JavaScriptConverter
{
    string subs = string.Empty;
    private const string _dateFormat = "MM/dd/yyyy";

    public JSONConverter(){}
    public JSONConverter(string subs){
        this.subs = subs;
    }

    public override IEnumerable<Type> SupportedTypes
    {
        get { return new Type[] { typeof(T) }; }
    }

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        T myclass = Activator.CreateInstance<T>();
        Regex myregex = new Regex(@"[a-z]");
        List<string> column = new List<string>();
        int k = 1;
        if (myclass != null)
        {
            PropertyInfo[] properties = myclass.GetType().GetProperties();

            foreach (var item in properties)
            {
                string key = myregex.Replace(item.Name, "");

                foreach (string s in column)
                {
                    if (s != null && s.Equals(key))
                    {
                        key += k.ToString(); k++;
                    }
                }
                column.Add(key);
                if (!dictionary.ContainsKey(key))
                    continue;
                item.SetValue(myclass, Convert.ChangeType(dictionary[key], item.PropertyType), null);
            }
        }
        return myclass;
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        var myclass = (T) obj;
        var result = new Dictionary<string, object>();
        
        if (myclass != null)
        {
            PropertyInfo[] properties = myclass.GetType().GetProperties();
            foreach (var item in properties)
            {
                if (subs.IndexOf(item.Name)>-1)
                    continue;
                object value = item.GetValue(myclass, null);
                if (item.PropertyType == typeof(DateTime))
                    value = ((DateTime)item.GetValue(myclass, null)).ToString(_dateFormat);
                result.Add(item.Name, value);
            }
        }
        return result;
    }
}